package io.gitee.kenewstar.dbmq.thread;

import io.gitee.kenewstar.dbmq.ConsumerTask;
import io.gitee.kenewstar.dbmq.data.DbDataHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.LockSupport;

/**
 * @author kenewstar
 */
public class WorkThreadPool {

    private static final Logger LOGGER = LoggerFactory.getLogger(WorkThreadPool.class);

    private DbDataHandler dbDataHandler;
    private List<ConsumerThread> threadList;
    private ClearThread clearThread;

    public WorkThreadPool() {}

    public WorkThreadPool(DbDataHandler dbDataHandler) {
        this.dbDataHandler = dbDataHandler;
    }

    public void initTaskList(List<ConsumerTask> taskList) {
        threadList = new ArrayList<>(taskList.size());
        taskList.forEach(task -> threadList.add(new ConsumerThread(task, dbDataHandler)));
        this.clearThread = new ClearThread(dbDataHandler, taskList);
    }

    public void pullMessageTaskRunning() {
        for (ConsumerThread consumerThread : threadList) {
            if (consumerThread.isNew()) {
                consumerThread.start();
            } else if (consumerThread.isWaiting()) {
                LockSupport.unpark(consumerThread);
            } else if (consumerThread.isRunning()) {
                LOGGER.debug("==============={} task running================", consumerThread.getName());
            }
        }

        if (clearThread.isNew()) {
            clearThread.start();
        } else if (clearThread.isWaiting()) {
            LockSupport.unpark(clearThread);
        } else if (clearThread.isRunning()) {
            LOGGER.debug("==============={} clear running================", clearThread.getName());
        }
    }


}
